package com.training.controller;

import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.training.dto.FeedbackTaskDto;
import com.training.entity.Address;
import com.training.entity.ConfirmAqiData;
import com.training.entity.PublicSurveillanceData;
import com.training.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * ClassName: FeedbackTaskController
 * Package: com.training.controller
 * Description: 反馈任务管理
 * @Author: wfz
 * @Create: 2024-06-07 - 13:56
 * @Version: v1.0
 */

@RestController
@RequestMapping("/feedbackTask")
@Tag(name = "反馈任务管理")
public class FeedbackTaskController {

    @Operation(summary = "获取分配给该网格员的反馈任务")
    @GetMapping("/list/{id}")
    public SaResult getFeedbackTaskList(@RequestParam(defaultValue = "1")Integer page,
                                    @RequestParam(defaultValue = "10")Integer pageSize,
                                    @RequestParam(defaultValue = "")String province,
                                    @RequestParam(defaultValue = "") String city,
                                    @PathVariable(name = "id") String inspectorId,
                                    LocalDateTime startDate, LocalDateTime endDate) {
        List<ConfirmAqiData> feedbackTask;
        if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
            feedbackTask = Db.lambdaQuery(ConfirmAqiData.class)
                    .eq(ConfirmAqiData::getInspectorId, inspectorId)
                    .orderByAsc(ConfirmAqiData::getIsConfirmed)
                    .list();
        } else {
            feedbackTask = Db.lambdaQuery(ConfirmAqiData.class)
                    .between(ConfirmAqiData::getUpdateTime, startDate, endDate)
                    .eq(ConfirmAqiData::getInspectorId, inspectorId)
                    .orderByAsc(ConfirmAqiData::getIsConfirmed)
                    .list();
        }
        feedbackTask = feedbackTask.stream().filter(e -> {
            Address address = Db.lambdaQuery(Address.class).eq(Address::getId, e.getAddressId())
                    .like(Address::getProvince, province).like(Address::getCity, city).one();
            return Objects.nonNull(address);
        }).toList();

        int start = (page - 1) * pageSize;
        int end = Math.min(page * pageSize, feedbackTask.size());
        List<ConfirmAqiData> confirmAqiDataList = feedbackTask.subList(start, end);

        List<FeedbackTaskDto> feedbackTaskDto = confirmAqiDataList.stream().map(e -> {
            PublicSurveillanceData surveillanceData = Db.getById(e.getSurveillanceId(), PublicSurveillanceData.class);
            User supervisor = Db.getById(surveillanceData.getSupervisorId(), User.class);
            Address address = Db.getById(e.getAddressId(), Address.class);
            return FeedbackTaskDto.builder()
                    .id(e.getId())
                    .supervisor(supervisor)
                    .address(address)
                    .estimatedLevel(surveillanceData.getEstimatedLevel())
                    .feedbackTime(surveillanceData.getFeedbackTime())
                    .description(surveillanceData.getDescription())
                    .isConfirmed(e.getIsConfirmed())
                    .build();
        }).toList();
        Map<String , Object> map = Map.of("total", feedbackTask.size(), "data", feedbackTaskDto);
        return SaResult.data(map);
    }

    @Operation(summary = "根据id获取反馈任务详情")
    @GetMapping("/detail/{id}")
    public SaResult getFeedbackTaskById(@PathVariable String id) {
        ConfirmAqiData confirmAqiData = Db.getById(id, ConfirmAqiData.class);
        PublicSurveillanceData surveillanceData = Db.getById(confirmAqiData.getSurveillanceId(), PublicSurveillanceData.class);
        User supervisor = Db.getById(surveillanceData.getSupervisorId(), User.class);
        Address address = Db.getById(confirmAqiData.getAddressId(), Address.class);
        FeedbackTaskDto feedbackTaskDto = FeedbackTaskDto.builder()
                .id(confirmAqiData.getId())
                .supervisor(supervisor)
                .address(address)
                .estimatedLevel(surveillanceData.getEstimatedLevel())
                .description(surveillanceData.getDescription())
                .feedbackTime(surveillanceData.getFeedbackTime())
                .isConfirmed(confirmAqiData.getIsConfirmed())
                .build();
        return SaResult.data(feedbackTaskDto);
    }

    @Operation(summary = "提交确认")
    @PostMapping("/confirm")
    public SaResult confirmRealData(@RequestBody ConfirmAqiData realData){
        ConfirmAqiData data = Db.lambdaQuery(ConfirmAqiData.class)
                .eq(ConfirmAqiData::getId, realData.getId()).one();
        if (Objects.isNull(data)) {
            return SaResult.error("数据不存在");
        } else if (data.getIsConfirmed() == 1){
            return SaResult.error("已确认");
        }
        data.setIsConfirmed(1);
        data.setSulfurDioxideConcentration(realData.getSulfurDioxideConcentration());
        data.setCarbonMonoxideConcentration(realData.getCarbonMonoxideConcentration());
        data.setParticulateMatter(realData.getParticulateMatter());
        data.setAqi(realData.getAqi());
        data.setUpdateTime(LocalDateTime.now());
        Db.lambdaUpdate(ConfirmAqiData.class).update(data);
        return SaResult.ok("确认成功");
    }
}
